//表单验证函数库

import Regex from './regex';

export const checkEmpty = (rule: any, value: any, callback: any) => {
  const { required } = rule;
  if (value) {
    const _value = (value + '').replace(/(^\s*)|(\s*$)/g, '');
    if (!_value) {
      callback(new Error('请输入内容'));
      return;
    }
    callback();
  } else if (required) {
    callback(new Error('请输入内容'));
  } else {
    callback();
  }
};

export const checkLoginNumber = (rule: any, value: any, callback: any) => {
  const { required } = rule;
  if (value) {
    value = (value + '').replace(/(^\s*)|(\s*$)/g, '');
    if (!/^[a-zA-Z0-9]{6,19}$/.test(value)) {
      callback(new Error('请输入6-19数字或字母'));
    } else {
      callback();
    }
  } else if (required) {
    callback(new Error('请输入6-19数字或字母'));
  } else {
    callback();
  }
};

export const checkRealName = (rule: any, value: any, callback: any) => {
  const { required } = rule;
  if (value) {
    if (value.length < 2 || value.length > 25) {
      callback(new Error('真实名字长度为2-25位'));
    }
    if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/g.test(value)) {
      callback(new Error('真实姓名只能输入中文或英文或数字'));
    }
    callback();
  } else if (required) {
    callback(new Error('请输入真实名字'));
  } else {
    callback();
  }
};

export const checkPhone = (value: string, callback: any) => {
  if (value) {
    if (!Regex.phone.test(value)) {
      callback('手机格式不对，请重新输入手机号码');
    }
    callback();
  } else {
    callback('请输入手机号');
  }
};

// 校验电话号码和手机号码
export const checkTelephone = (rule: any, value: any, callback: any) => {
  const { required } = rule;
  if (value) {
    if (!Regex.phone.test(value) && !/0\d{2,3}-\d{7,8}/.test(value)) {
      callback(new Error('电话格式不对，请重新输入电话号码'));
    }
    callback();
  } else if (required) {
    callback(new Error('请输入电话手机'));
  } else {
    callback();
  }
};

export const checkEmail = (rule: any, value: any, callback: any) => {
  const { required } = rule;
  if (value) {
    if (!Regex.email.test(value)) {
      callback(new Error('邮箱格式不对，请重新输入邮箱'));
    }
    callback();
  } else if (required) {
    callback(new Error('请输入邮箱'));
  } else {
    callback();
  }
};
